package com.fancy.learncenter.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.AddDiscussDataBean;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.DiscussDataBean;
import com.fancy.learncenter.bean.MedioDataBean;
import com.fancy.learncenter.bean.PraiseDataBean;
import com.fancy.learncenter.bean.ShareDataBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.activity.base.MallCommonH5Activity;
import com.fancy.learncenter.ui.adapter.FragmentPlayAuidoDiscussAdapter;
import com.fancy.learncenter.ui.adapter.base.CommonRecycleViewAdapter;
import com.fancy.learncenter.ui.adapter.base.CustomViewHold;
import com.fancy.learncenter.ui.callback.SampleListener;
import com.fancy.learncenter.ui.view.CustomListGSYVideoPlayer;
import com.fancy.learncenter.ui.view.SharePopupWindow;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.utils.WXShareUtil;
import com.shuyu.gsyvideoplayer.GSYPreViewManager;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.model.GSYVideoModel;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.CustomGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.ListGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 视频播放页
 */
public class PlayVedioActivity extends BaseActivity implements View.OnTouchListener {

    TextView content;
    RelativeLayout topView;
    RecyclerView imgList;
    FragmentPlayAuidoDiscussAdapter discussAdapter;


    @Bind(R.id.vedio_play)
    CustomGSYVideoPlayer detailPlayer;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.isPraise)
    ImageView isPraise;
    @Bind(R.id.praise_num)
    TextView praiseNum;
    @Bind(R.id.praise)
    LinearLayout praise;
    @Bind(R.id.rootView)
    RelativeLayout rootView;
    @Bind(R.id.dicuss)
    EditText dicuss;
    @Bind(R.id.dis_ll)
    LinearLayout disLl;
    @Bind(R.id.shop_cart_image)
    ImageView shopCartImage;
    @Bind(R.id.shop_cart_text)
    TextView shopCartText;
    @Bind(R.id.back_image)
    ImageView backImage;
    @Bind(R.id.right_img)
    ImageView rightImg;
    SimpleDraweeView emptyView; //空白页

    float oldY = 0;
    float nowY = 0;
    private OrientationUtils orientationUtils;


    //封面图
    String showResourceCoverImg = "";
    // 播放列表
    String playLink = "";
    //  资源名称
    String showResourceName = "";
    //  资源ID
    int showResourceId = 0;

    String intro = "";

    SharePopupWindow sharePopupWindow;


    ArrayList<MedioDataBean.DetailBean.ResourceVOListBean> imgsData;

    ImgsAdatapter imgsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_vedio, Status.STATUS);
        ButterKnife.bind(this);

        initView();
        initData();
//        initVedio();
        getDetailData();
        addPV();
    }

    private boolean isPlay;
    private boolean isPause;

    private void initData() {

        showResourceId = getIntent().getIntExtra("showResourceId", 0);
        showResourceName = getIntent().getStringExtra(Constant.showResourceName);
        rightImg.setVisibility(View.VISIBLE);
        rightImg.setImageResource(R.mipmap.share);
        rightImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sharePopupWindow == null) {
                    sharePopupWindow = new SharePopupWindow(PlayVedioActivity.this, rootView);
                    sharePopupWindow.setShareCallBack(new SharePopupWindow.ShareCallBack() {
                        @Override
                        public void wxCallBack() {
                            if (shareVOBean != null) {
                                String urlPic = shareVOBean.getImageUrl();
                                String title = shareVOBean.getTitle();
                                String content = shareVOBean.getSubTitle();
                                String linkYrl = shareVOBean.getUrl();
                                WXShareUtil.getInstance(PlayVedioActivity.this).shareWebPage(urlPic, title, content, linkYrl, false);
                            } else {
                                getShareData(false);
                            }
                        }

                        @Override
                        public void wxFriendCallBack() {
                            if (shareVOBean != null) {
                                String urlPic = shareVOBean.getImageUrl();
                                String title = shareVOBean.getTitle();
                                String content = shareVOBean.getSubTitle();
                                String linkYrl = shareVOBean.getUrl();
                                WXShareUtil.getInstance(PlayVedioActivity.this).shareWebPage(urlPic, title, content, linkYrl, true);
                            } else {
                                getShareData(true);
                            }
                        }
                    });
                }
                sharePopupWindow.showPopupWindow();
            }
        });
//        setRightImg(R.mipmap.share, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });


        ArrayList data = new ArrayList();

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        discussAdapter = new FragmentPlayAuidoDiscussAdapter(this, data);
        recyclerView.setAdapter(discussAdapter);
        discussAdapter.setHeaderView(topView, recyclerView);
        recyclerView.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                oldY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                nowY = event.getY();
                break;
            case MotionEvent.ACTION_UP:
                if (Math.abs(oldY - nowY) > 50) {
                    showSoftInputFromWindow(false);
                    disLl.setVisibility(View.GONE);
                }
                break;
        }
        return false;
    }

    private void initView() {
        topView = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.activity_play_vedio_top, null);
        imgList = (RecyclerView) topView.findViewById(R.id.imgList);
//        detailPlayer = (CustomListGSYVideoPlayer) topView.findViewById(R.id.vedio_play);
        content = (TextView) topView.findViewById(R.id.content);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        emptyView = (SimpleDraweeView) topView.findViewById(R.id.empty_view);
        //图片列表
        imgList = (RecyclerView) topView.findViewById(R.id.imgList);
        imgsData = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        imgList.setLayoutManager(manager);
        detailPlayer.getBackButton().setVisibility(View.GONE);
        imgsAdapter = new ImgsAdatapter(this, imgsData);
        imgList.setAdapter(imgsAdapter);
        backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    private void initVedio() {

        LogUtil.MyLog("initVedio", "=====initVedio====" + playLink);
        content.setText(intro);
        List<GSYVideoModel> urls = new ArrayList<>();
        urls.add(new GSYVideoModel(playLink, showResourceName));
//        detailPlayer.setUp(urls, false, 0, "");
        detailPlayer.setUp(playLink, false, showResourceName);

//        //增加封面
        SimpleDraweeView imageView = new SimpleDraweeView(this);
        GenericDraweeHierarchy hierarchy = imageView.getHierarchy();
        hierarchy.setPlaceholderImage(R.mipmap.default_vedio);
        hierarchy.setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER);
        imageView.setHierarchy(hierarchy);
        imageView.setImageURI(showResourceCoverImg);

        detailPlayer.setThumbImageView(imageView);
        detailPlayer.startPlayLogic();
        resolveNormalVideoUI();

        //外部辅助的旋转，帮助全屏
        orientationUtils = new OrientationUtils(this, detailPlayer);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);

        detailPlayer.setIsTouchWiget(true);
        //关闭自动旋转
        detailPlayer.setRotateViewAuto(false);
        detailPlayer.setLockLand(false);
        detailPlayer.setShowFullAnimation(false);
        detailPlayer.setNeedLockFull(true);
        //自动播放
        detailPlayer.startPlayLogic();
        detailPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //直接横屏
                orientationUtils.resolveByClick();
                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                detailPlayer.startWindowFullscreen(PlayVedioActivity.this, true, true);
            }
        });

        detailPlayer.setStandardVideoAllCallBack(new SampleListener() {
            @Override
            public void onPrepared(String url, Object... objects) {
                super.onPrepared(url, objects);
                //开始播放了才能旋转和全屏
                orientationUtils.setEnable(true);
                isPlay = true;
            }

            @Override
            public void onAutoComplete(String url, Object... objects) {
                super.onAutoComplete(url, objects);
            }

            @Override
            public void onClickStartError(String url, Object... objects) {
                super.onClickStartError(url, objects);
            }

            @Override
            public void onQuitFullscreen(String url, Object... objects) {
                super.onQuitFullscreen(url, objects);
                if (orientationUtils != null) {
                    orientationUtils.backToProtVideo();
                }
            }
        });

        detailPlayer.setLockClickListener(new LockClickListener() {
            @Override
            public void onClick(View view, boolean lock) {
                if (orientationUtils != null) {
                    //配合下方的onConfigurationChanged
                    orientationUtils.setEnable(!lock);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoPlayer.releaseAllVideos();
        if (orientationUtils != null)
            orientationUtils.releaseListener();
    }


    @Override
    public void onBackPressed() {

        //横屏返回到竖屏，返回正常状态
        if (orientationUtils != null && orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            detailPlayer.getFullscreenButton().performClick();
            return;
        }

        if (detailPlayer != null) {
            //释放资源
            detailPlayer.setStandardVideoAllCallBack(null);
            GSYVideoPlayer.releaseAllVideos();
        }
//        if (StandardGSYVideoPlayer.backFromWindowFull(this)) {
//            return;
//        }

        if (disLl.getVisibility() == View.VISIBLE) {
            disLl.setVisibility(View.GONE);
            showSoftInputFromWindow(false);
            return;
        }


        super.onBackPressed();
    }


    @Override
    protected void onPause() {
        super.onPause();
        isPause = true;
        detailPlayer.onVideoPause();
//        GSYPreViewManager.instance().getMediaPlayer().pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isPause = false;
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            if (newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_USER) {
                if (!detailPlayer.isIfCurrentIsFullscreen()) {
                    detailPlayer.startWindowFullscreen(PlayVedioActivity.this, true, true);
                }
            } else {
                //新版本isIfCurrentIsFullscreen的标志位内部提前设置了，所以不会和手动点击冲突
                if (detailPlayer.isIfCurrentIsFullscreen()) {
                    StandardGSYVideoPlayer.backFromWindowFull(this);
                }
                if (orientationUtils != null) {
                    orientationUtils.setEnable(true);
                }
            }
        }

    }


    private void resolveNormalVideoUI() {
        //增加title
        detailPlayer.getTitleTextView().setVisibility(View.GONE);
        detailPlayer.getTitleTextView().setText("测试视频");
        detailPlayer.getBackButton().setVisibility(View.GONE);
    }

    @OnClick({R.id.praise, R.id.shop_cart, R.id.dis_bt, R.id.send})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send:
                if (!TextUtils.isEmpty(dicuss.getText().toString().trim())) {

                    addComment(dicuss.getText().toString());
                } else {
                    ToastUtil.show("评论不能为空");
                }

                break;
            case R.id.dis_bt:
                disLl.setVisibility(View.VISIBLE);
                showSoftInputFromWindow(true);
                break;
            case R.id.praise:
                addPraiseNum();
                break;
            case R.id.shop_cart:
                if (!TextUtils.isEmpty(buyUrl)) {
                    Intent intent = new Intent(this, MallCommonH5Activity.class);
                    intent.putExtra(MallCommonH5Activity.URL_KEY, buyUrl);
                    startActivity(intent);
                } else {
                    shopCartImage.getDrawable().setAlpha(127);
                    shopCartText.setAlpha(0.5f);
//                    ToastUtil.show("暂无购买商品");
                }
                break;
        }
    }

    class ImgsAdatapter extends CommonRecycleViewAdapter<MedioDataBean.DetailBean.ResourceVOListBean> {


        public ImgsAdatapter(Context mContext, List<MedioDataBean.DetailBean.ResourceVOListBean> itemDatas) {
            super(mContext, R.layout.activity_play_audio_img_item, itemDatas);
        }

        @Override
        public void bindView(CustomViewHold customViewHold, MedioDataBean.DetailBean.ResourceVOListBean item, int position) {
            SimpleDraweeView simpleDraweeView = (SimpleDraweeView) customViewHold.getRoorView();
            simpleDraweeView.setImageURI(item.getWholeCoverImg());
        }
    }


    private void getDetailData() {

        Map map = new HashMap();
        map.put("entityId", showResourceId);
        map.put("type", 3);
        HttpMehtod.getInstance().getPraiseNum(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<PraiseDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), PraiseDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<PraiseDataBean>() {
                    @Override
                    public void success(PraiseDataBean dataBean) {
                        if (dataBean.getMPraiseVO().getIsHadPraise() == 1) {
                            isPraise.setImageResource(R.mipmap.like);

                            praise.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            });
                        }
                        if (!TextUtils.isEmpty(dataBean.getMPraiseVO().getPraiseNums())) {
                            praiseNum.setText(dataBean.getMPraiseVO().getPraiseNums());
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });

        getDiscuss();
        getShowDetail();
    }

    private void getDiscuss() {
        Map map = new HashMap();
        map.put("entityId", showResourceId);
        map.put("type", 3);
        HttpMehtod.getInstance().getDiscuss(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<DiscussDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), DiscussDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<DiscussDataBean>() {
                    @Override
                    public void success(DiscussDataBean dataBean) {
                        discussAdapter.notifyDataSetChanged(dataBean.getCommentsVOList());
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }

    String buyUrl;

    private void getShowDetail() {
        HttpMehtod.getInstance().getMedioDetail(showResourceId, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                //解析数据
                BaseBean<MedioDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), MedioDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<MedioDataBean>() {
                    @Override
                    public void success(MedioDataBean dataBean) {
                        buyUrl = dataBean.getDetail().getBuyUrl();
                        playLink = dataBean.getDetail().getWholePlayLink();
                        showResourceCoverImg = dataBean.getDetail().getWholeShowResourceCoverImg();
                        intro = dataBean.getDetail().getIntro();

                        if (dataBean.getDetail().getResourceVOList() != null) {
                            imgsData.addAll(dataBean.getDetail().getResourceVOList());
                        }
                        if (imgsData.size() > 0) {
                            imgList.setVisibility(View.VISIBLE);
                            emptyView.setVisibility(View.GONE);
                        } else {
                            imgList.setVisibility(View.GONE);
                            emptyView.setVisibility(View.VISIBLE);
                        }

                        if (TextUtils.isEmpty(buyUrl)) {
                            shopCartImage.getDrawable().setAlpha(127);
                            shopCartText.setAlpha(0.5f);
                        } else {
                            shopCartImage.getDrawable().setAlpha(255);
                            shopCartText.setAlpha(1f);
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }

            @Override
            public void onCompleted() {
                super.onCompleted();
                initVedio();
                imgsAdapter.notifyDataSetChanged();


            }
        });
    }

    private void addPraiseNum() {
        Map map = new HashMap();
        map.put("entityId", showResourceId);
        map.put("type", 3);

        HttpMehtod.getInstance().addPraiseNum(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<PraiseDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), PraiseDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<PraiseDataBean>() {
                    @Override
                    public void success(PraiseDataBean dataBean) {
                        if (dataBean.getMPraiseVO().getIsHadPraise() == 1) {
                            isPraise.setImageResource(R.mipmap.like);

                            praise.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            });
                        }
                        praiseNum.setText(dataBean.getMPraiseVO().getPraiseNums());

                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }

    private void addComment(String content) {
        Map map = new HashMap();
        map.put("entityId", showResourceId);
        map.put("type", 3);
        map.put("content", content);

        HttpMehtod.getInstance().addComment(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<AddDiscussDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), AddDiscussDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<AddDiscussDataBean>() {
                    @Override
                    public void success(AddDiscussDataBean dataBean) {
                        if (dataBean.getResult() == 1) {
                            disLl.setVisibility(View.GONE);
                            showSoftInputFromWindow(false);
                            dicuss.setText("");
                            ToastUtil.show("评论成功");

                            getDiscuss();
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }

    ShareDataBean.ShareVOBean shareVOBean;

    private void getShareData(final boolean isFirend) {
        Map map = new HashMap();
        map.put("entityId", showResourceId);
        map.put("shareType", 1);

        HttpMehtod.getInstance().getShareData(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<ShareDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), ShareDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<ShareDataBean>() {
                    @Override
                    public void success(ShareDataBean dataBean) {
                        shareVOBean = dataBean.getShareVO();
                        String urlPic = shareVOBean.getImageUrl();
                        String title = shareVOBean.getTitle();
                        String content = shareVOBean.getSubTitle();
                        String linkYrl = shareVOBean.getUrl();
                        WXShareUtil.getInstance(PlayVedioActivity.this).shareWebPage(urlPic, title, content, linkYrl, isFirend);
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }

    private void addPV() {
        Map map = new HashMap();
        map.put("entityId", showResourceId);
        map.put("type", 3);
        HttpMehtod.getInstance().addPV(map, new CustomNetSubscriber(this, false) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
            }
        });
    }


    /**
     * EditText获取焦点并显示软键盘
     */
    public void showSoftInputFromWindow(boolean isShow) {
        dicuss.setFocusable(true);
        dicuss.setFocusableInTouchMode(true);
        dicuss.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (isShow) {
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

        } else {
            imm.hideSoftInputFromWindow(dicuss.getWindowToken(), 0); //强制隐藏键盘
        }
    }


}
